﻿using JavaCodeGeneratorConsole.entity;
using SQLite;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JavaCodeGeneratorConsole.utils
{
    public class DbUtils
    {

        private static SQLiteConnection connection;
        private static string dbPath;

        /// <summary>
        /// 连接Sqlite
        /// </summary>
        /// <param name="dbPath">数据库路径</param>
        /// <param name="username">数据库用户名</param>
        /// <param name="password">数据库密码</param>
        public static List<TableInfo> GetTableInfos(string dbPath)
        {
            if (dbPath == null || dbPath.Length == 0)
            {
                throw new Exception("路径不能为空！");
            }
            connection = new SQLiteConnection(dbPath);
            string queryTableInfoSql = "select (select count(*) from sqlite_master b where a.name >= b.name) as idx, name from sqlite_master a where name <> 'sqlite_sequence' ORDER BY idx;";
            List<TableInfo> tableInfoList = connection.Query<TableInfo>(queryTableInfoSql);

            if (tableInfoList != null && tableInfoList.Count > 0)
            {
                for (int i = 0; i < tableInfoList.Count; i++)
                {
                    //Console.WriteLine("name=" + tableInfoList[i].name);
                    tableInfoList[i].tableDatas = QueryTableData(tableInfoList[i].name);
                }
            }
            return tableInfoList;

        }

        private static List<TableColunm> QueryTableData(string tableName)
        {
            string queryTableDataSql = $"PRAGMA table_info('{tableName}');";
            List<TableColunm> tableDataList = connection.Query<TableColunm>(queryTableDataSql);
            //Console.WriteLine(tableDataList);
            return tableDataList;
        }
    }
}
